package com.itheima.rpc.server.registry.zk;


import com.itheima.rpc.annotation.HrpcService;
import com.itheima.rpc.server.config.RpcServerConfiguration;
import com.itheima.rpc.server.registry.RpcRegister;
import com.itheima.rpc.spring.SpringBeanFactory;
import com.itheima.rpc.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Slf4j
@DependsOn(value = "springBeanFactory")
@Component
public class ZkRegister implements RpcRegister {

    @Resource
    private ServerZKit serverZKit;
    @Resource
    private RpcServerConfiguration rpcServerConfiguration;

    @Override
    public void serverRegister() {
        //获取有@HrpcService注解的实现类
        Map<String, Object> map = SpringBeanFactory.getBeanListByAnnotationClass(HrpcService.class);
        if (!map.isEmpty()) {
            //创建根节点
            serverZKit.createRootNode();

            //获取服务所在机器的ip
            String ip = IpUtil.getRealIp();

            for (Object bean : map.values()) {
                //获取实现类上面的@HrpcService注解
                HrpcService hrpcService = bean.getClass().getAnnotation(HrpcService.class);
                //拿到@HrpcService注解里面的interfaceClass属性
                Class<?> interfaceClass = hrpcService.interfaceClass();
                String serviceName = interfaceClass.getName();
                //注册服务节点
                serverZKit.createPersistentNode(serviceName);
                //注册服务通信端口
                int rpcPort = rpcServerConfiguration.getRpcPort();
                String node = ip + ":" + rpcPort;
                serverZKit.createNode(serviceName + "/" + node);
                log.info("服务{}-{}注册成功", serviceName, node);
            }
        }


    }
}
